import {
	mapMutations
} from 'vuex'
import WebSocket from '@/websocket/websocket.js'
export default {
	...mapMutations([
		'upUserInfo'
	]),
	connect() {
		WebSocket.init().then((client) => {
			let userId = uni.getStorageSync('userId')
			console.log("初始化获取", `/topic/message/${userId}`)
			client.subscribe( // 订阅
				`/topic/message/${userId}`,
				(frame) => {
					let params = JSON.parse(frame.body);
					//判断数组是新聊天
					let isNewUser = this.list.some(item => item.userId === params.sendUserId);
					console.log("判断数组是新聊天", isNewUser)
					if (!isNewUser) {
						let obj = {
							avatar: params.sendUserAvatar,
							content: params.content,
							createTime: params.createTime,
							userId: params.sendUserId,
							nickname: params.sendUserName,
							type: params.type,
							unreadCount: 1,
						}
						console.log("新用户信息", obj)
						this.list.unshift(obj);
					} else {
						this.list.forEach((item, index) => {

							if (item.userId == params.sendUserId) {
								// console.log(this.list)
								// this.list.splice(index,1)
								item.avatar = params.sendUserAvatar;
								item.content = params.content;
								item.createTime = params.createTime;
								item.userId = params.sendUserId;
								item.nickname = params.sendUserName;
								item.unreadCount = item.unreadCount + 1;
								item.type = params.type;
								console.log("已经存在用户信息", item)
								// this.list.unshift(this.list.splice(index, 1)[0]);

							}
						})
					}

					console.log(params) // 接收到的数据
					wx.vibrateShort()
				}, {
					ack: 'client'
				} // 消息不会被确认接收，不确认每次连接都会推送
			)
		})


	},
	connectlisenter() {
		// 监听 WebSocket 连接关闭事件
		WebSocket.setCloseCallback((res) => {
			console.log('WebSocket 已关闭00！', res);
			// 在此处添加关闭事件的逻辑处理
			// 重连
			this.reconnectId = setTimeout(() => {
				this.reconnect()
			}, this.reconnectInterval)
		});
	},
	//重新连接
	reconnect() {

		this.connect()
	},
	unsubscribe() {
		WebSocket.disconnect()
		// 停止重连事件
		if (this.reconnectId) {
			clearTimeout(this.reconnectId)
			this.reconnectId = null
		}
	},
	toNotificationLike() {
		uni.navigateTo({
			url: '/pages/index/notificationLike'
		})
	},
	toNotificationFollow() {
		uni.navigateTo({
			url: '/pages/index/notificationFollow'
		})
	},
	toNotificationComment() {
		uni.navigateTo({
			url: '/pages/index/notificationComment'
		})
	},

	showSubscribeMsg() {
		// this.$refs.subscribeMsg.open()
		let that = this
		// 	uni.getSetting({
		// 	  withSubscriptions: true,
		// 	  success(res) {
		// 		console.log(res)
		// 		if (res.subscriptionsSetting.mainSwitch) { // 用户打开了订阅消息总开关
		// 			console.log(res.subscriptionsSetting.itemSettings)
		// 			 if (res.subscriptionsSetting.itemSettings != null) { // 用户同意总是保持是否推送消息的选择, 这里表示以后不会再拉起推送消息的授权
		// 			  let moIdState = res.subscriptionsSetting.itemSettings['nH8STlo5pO_LkytTMPI8HYZsdct6u_oRGQuiF8IX83s']; // 用户同意的消息模板id
		// 			  if (moIdState === 'accept') {
		// 				console.log('接受了消息推送');
		// 			  } else if (moIdState === 'reject') {
		// 				console.log('拒绝了消息推送');
		// 			  } else if (moIdState === 'ban') {
		// 				console.log("已被后台封禁");
		// 			  }
		// 			}
		// 		} else {
		// 		//是否提示用户前去设置
		// 		 //  uni.openSetting({
		// 			// withSubscriptions: true,
		// 		 //  })
		// 		  //这里做用户未开启订阅总开关的操作
		// 		  that.$toast.confirm({
		// 		  	content: '为了更好服务,请订阅信息',
		// 		  	confirmText: '订阅',
		// 		  	callback: result => {
		// 		  		if (result) {
		// 		  			that.subscribeMessages()
		// 		  		}
		// 		  	}
		// 		  })

		// 		}
		// 	  }
		// 	})



	},
	//订阅微信消息
	subscribeMessages() {

		uni.requestSubscribeMessage({
			tmplIds: ['nH8STlo5pO_LkytTMPI8HYZsdct6u_oRGQuiF8IX83s'],
			success(res) {
				console.log("订阅成", res)
			}
		});
	},
	toAdvisory(item) {
		let that = this
		if (that.atLoading) {
			//禁止多次点击
			return false
		}
		that.atLoading = true
		let name = item.merchantName ? item.merchantName : item.userName
		uni.navigateTo({
			url: '/pages/index/advisory?user_id=' + item.userId + '&username=' + name
		})
		// this.$myRouter.to('/pages/index/advisory?u_id=' + item.uid + '&park_area_id=' + item.park_area_id)
		setTimeout(() => { //延时指定时间后，再解冻
			that.atLoading = false;
		}, 1000);

	},
	delChat(e, index) {
		let that = this
		that.$httpRequest.get({
			that: that,
			url: 'wechat/deleteChatUser',
			params: {
				userId: e.data.userId
			},
			success: res => {
				if (res.code === that.$httpConfig.SUCCESS_CODE) {
					that.list.splice(index, 1)
				} else {

				}
			}
		})
		// console.log("删除聊天",e)
	},
	getUserInfo() {
		let that = this
		that.$httpRequest.get({
			that: that,
			url: 'wechat/info',
			params: {

			},
			success: res => {
				if (res.code === that.$httpConfig.SUCCESS_CODE) {
					that.upUserInfo(res.data)
					// console.log(that.userInfo)
					// setTimeout(function () {
					// 		    uni.hideLoading();
					// 		}, 200);
				} else {
					that.upUserInfo({})
				}
			}
		})
	},
	changeTime() {
		this.timeRequest = setInterval(() => {
			// this.getPageList()
			this.getUserInfo()
			// console.log("启动定时器,信息列表")
		}, 4700)
	},
	getPageList() {
		let that = this
		that.$httpRequest.get({
			url: 'wechat/getAllChatUser',
			params: {

			},
			success: res => {
				if (res.code === that.$httpConfig.SUCCESS_CODE) {
					that.list = res.data

				}
			}
		}, false)
	},
	read() {
		let that = this
		that.$httpRequest.get({
			url: 'wechat/readAllMessage',
			params: {

			},
			success: res => {
				if (res.code === that.$httpConfig.SUCCESS_CODE) {
					that.list.forEach((item, index) => {
						item.unreadCount = 0
					})

				}
			}
		}, false)
	},
	toSystemMsg() {
		uni.navigateTo({
			url: '/pages/index/systemMsg'
		})
	},
}